﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UpdateServers.Models;

namespace UpdateServers.Command
{
    /// <summary>
    /// 客户端
    /// </summary>
    public class SocketClients
    {
        /// <summary>
        /// 服务监听IP地址
        /// </summary>
        private IPEndPoint IPAddr { get; set; }
        /// <summary>
        /// 文件夹地址
        /// </summary>
        public string FilePath { get; set; }
        /// <summary>
        /// 文件全名
        /// </summary>
        public string FileFullName { get; set; }
        /// <summary>
        /// 客户端
        /// </summary>
        private Socket ClientServer { get; set; }

        private static object filelooker = new object();

        /// <summary>
        /// 构造连接
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public SocketClients(String ip, int port)
        {
            IPAddress ipa = IPAddress.Parse(ip);
            this.IPAddr = new IPEndPoint(ipa, port);

        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <returns></returns>
        public bool Connect()
        {
            bool result = false;
            try
            {
                this.ClientServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this.ClientServer.Connect(this.IPAddr);
                this.ClientServer.ReceiveTimeout = 3000;
                this.ClientServer.SendTimeout = 3000;
                result = true;
            }
            catch (Exception ex)
            {
                result = false;

            }
            return result;
        }
        /// <summary>
        /// 获取是否连接成功
        /// </summary>
        /// <returns></returns>
        public bool GetConnected()
        {

            if (this.ClientServer != null)
            {
                try
                {
                    this.ClientServer.Send(new byte[] { 1 });
                }
                catch (Exception)
                {
                    return false;
                }
                return this.ClientServer.Connected;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="text">消息内容</param>
        /// <returns></returns>
        public bool SendMessage(string text)
        {
            if (text != null)
            {
                try
                {
                    if (this.ClientServer.Connected)
                    {
                        byte[] sendbytes = Encoding.UTF8.GetBytes(text);
                        var index = this.ClientServer.Send(sendbytes);
                        return index > 0;
                    }
                    else
                    {
                        return false;
                    }

                }
                catch (Exception)
                {
                }

            }
            return false;
        }
        /// <summary>
        /// 获取文件
        /// </summary>
        public void GetFile()
        {
            if (this.ClientServer.Connected)
            {

                byte[] buffer = new byte[1024];
                long len = 0;
                int size = 0;
                if (!Directory.Exists(this.FilePath))
                {
                    Directory.CreateDirectory(this.FilePath);
                }
                lock (filelooker)
                {
                    var filename = $"{this.FilePath}\\DownFile.data";
                    FileStream fs = new FileStream(filename, FileMode.Create);
                    try
                    {

                        while (true)
                        {
                            size = this.ClientServer.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                            if (size == 1 && buffer[0] == 1)
                            {
                                continue;
                            }
                            if (size > 0)
                            {
                                fs.Write(buffer, 0, size);
                                len += size;
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        SocketException se = ex as SocketException;
                        if (se?.ErrorCode == 10060 && len > 0)
                        {
                            len = 0;
                            fs.Flush();
                            fs.Close();
                            //修改文件后缀
                            FileInfo fi = new FileInfo(filename);
                            var newfilename = this.FilePath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip";
                            fi.MoveTo(newfilename, true);
                            //获取文件全名
                            FileFullName = newfilename;
                            Loger.Log($"{FileFullName}更新包获取完成！");
                            var json = new ServerModel()
                            {
                                ClientIp = this.GetLocalIp(),
                                UpdateTime = DateTime.Now,
                                 UpdateState = "已接收"
                            };
                            this.SendMessage(json.ToJsonString());

                        }

                    }
                    finally
                    {
                        fs.Close();
                    }
                }

            }
        }
        /// <summary>
        /// 获取消息
        /// </summary>
        /// <returns></returns>
        public string GetMessage()
        {
            string result = string.Empty;
            byte[] rescbtye = new byte[1024];
            int index = this.ClientServer.Receive(rescbtye, rescbtye.Length, SocketFlags.None);
            result += Encoding.UTF8.GetString(rescbtye, 0, index);
            return result;

        }
        /// <summary>
        ///  获取本地IP
        /// </summary>
        /// <returns></returns>
        public string GetLocalIp()
        {
            var addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            var ip = addressList.FirstOrDefault(address => address.AddressFamily == AddressFamily.InterNetwork)?.ToString();
            return ip;
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Close()
        {

            this.ClientServer?.Close();
            this.ClientServer?.Dispose();
        }
    }
}
